<?php
 
defined("_VALID_ACCESS") || die('Direct access forbidden');
 
class SCTV_RequirementCommon extends ModuleCommon {
 
 	public static $leightbox_ready = array();
	public static $last_location = null;
	
    public static function menu() {
    	$menus[__('SCTV')] = array('__submenu__' => 1);
		
		$menus[__('SCTV')][__('Requirement')] = array();
		
		if(Base_AclCommon::check_permission('Waiting for Technical Support'))
			$menus[__('SCTV')][__('Waiting for Technical Support')] = array('__function__'=>'waiting_for_technical_support');
		
		if(Base_AclCommon::check_permission('Waiting for Business Support'))
			$menus[__('SCTV')][__('Waiting for Business Support')] = array('__function__'=>'waiting_for_business_support');
				
		$menus[__('SCTV')][__('Your incomplete requirement')] = array('__function__'=>'your_incompleted_requirement');
		
		if(Base_AclCommon::check_permission('Waiting for Accountant Support'))
			$menus[__('SCTV')][__('Waiting for Accountant Support')] = array('__function__'=>'waiting_for_accountant_support');
		
		return $menus;		
    }
	public static function defaults()
	{
		return array('customer_group'=>1, 'status'=>0, 'input_date'=>date('Y-m-d'), 'input_time'=>date('H:i:s'),'charge'=>0);
	}
	public static function process_request($data, $mode) {
        switch($mode) {        	
        	case 'adding':				
                $data['active']=true;
				$data['delivery_date']=$data['input_date'];
				eval_js('jQuery(".Utils_TabbedBrowser_div").attr("style","display:none");');
                break;
            case 'added':
                Utils_RecordBrowserCommon::update_record('SCTV_Requirement',$data['id'],array('requirement_code'=>$data['id']), false, null, true);
				Utils_RecordBrowserCommon::new_record('SCTV_StatusHistory', array('requirement'=>$data['id'], 'date_time'=>time(), 'employee'=>Utils_RecordBrowserCommon::get_id('contact','login',$data['created_by']), 'status'=>$data['status']));
                break;
			case 'view':												
				eval_js('var jump_to_record_input=$("jump_to_record_input");jump_to_record_input.style.display = "";jump_to_record_input.style.width = "150px";document.getElementById("jump_to_record_input").setAttribute("placeholder","Tìm theo mã lắp đặt");');
				if(Utils_RecordBrowserCommon::get_access('SCTV_Requirement', 'add'))
				{
					Base_ActionBarCommon::add(
						'add',
						__('New'),
						Utils_RecordBrowserCommon::create_new_record_href(
							'SCTV_Requirement', 
							SCTV_RequirementCommon::defaults(),			
							'none', false
						));	
				}				
				break;
            default:
                break;
        }
        return $data;
    }
	public static function display_requirement_code($record, $nolink){
		return Utils_RecordBrowserCommon::create_linked_label_r('SCTV_Requirement', 'requirement_code', $record, $nolink);	
	}
	public static function display_customer_name($record, $nolink) {
		return Utils_RecordBrowserCommon::create_linked_label_r('SCTV_Requirement', 'Customer Name', $record, $nolink);
    }
	public static function display_cable_status($record, $nolink, $desc) {
        return SCTV_RequirementCommon::get_cable_status_name($record['cable_status']);
    }
	public static function QFfield_status(&$form, $field, $label, $mode, $default, $desc, $rb_obj){
		if($mode=='add')
		{
			$data = Utils_CommonDataCommon::get_translated_array('SCTV/Requirement/Status');
			$form->addElement('select', $field, $label, array(0=>$data[0]), array('id'=>$field)); 
        	$form->setDefaults(array($field=>$default));
		}
		elseif($mode=='edit')
		{
			$form->addElement('commondata', $field, $label, 'SCTV/Requirement/Status', array('empty_option'=>false), array('id'=>$field)); 
        	$form->setDefaults(array($field=>$default));
		}
		else
		{
			$val = self::display_status($rb_obj->record, false, $desc);
			//$data = Utils_CommonDataCommon::get_translated_array('SCTV/Requirement/Status'); 
    		$form->addElement('static', $field, $label, $val);
     	}
    } 
	public static function QFfield_cable_status(&$form, $field, $label, $mode, $default, $desc, $rb_obj){		
		if ($mode=='add' || $mode=='edit')
		{
			$form->addElement('select', $field, $label, array(''=>'---', '1'=>__('New cable'), '0'=>__('Addition cable')), array('id'=>$field));
            $form->setDefaults(array($field=>$default));
		}
		else
		{
        	$form->addElement('static', $field, $label, SCTV_RequirementCommon::get_cable_status_name($default));
        }
    }
	public static function display_deployment_cable_status($record, $nolink, $desc) {
        return SCTV_RequirementCommon::get_cable_status_name($record['deployment_cable_status']);
    } 
	public static function QFfield_deployment_cable_status(&$form, $field, $label, $mode, $default, $desc, $rb_obj){		
		if ($mode=='add' || $mode=='edit')
		{
			$form->addElement('select', $field, $label, array(''=>'---', '1'=>__('New cable'), '0'=>__('Addition cable')), array('id'=>$field));
            $form->setDefaults(array($field=>$default));
		}
		else
		{
        	$form->addElement('static', $field, $label, SCTV_RequirementCommon::get_cable_status_name($default));
        }
    }
	
	public static function display_street($record, $nolink) {
		return SCTV_RequirementCommon::format_street($record['street'], $nolink);
	}
	public static function display_status($record, $nolink, $desc) {
		$prefix = 'SCTV_requirement_leightbox';
		$record_id = $record['id'];
		$v = $record[$desc['id']];
		if (!$v) $v = 0;
		$status = Utils_CommonDataCommon::get_translated_array('SCTV/Requirement/Status');
		
		$custom_view = Module::static_get_module_variable('SCTV_Requirement', 'custom_view', null);
		
		$return = null;
		if($v == 1 || $v == 2 || 
			($custom_view == null && !Utils_RecordBrowserCommon::get_access('SCTV_Requirement', 'add', $record)) ||
			(
				($custom_view == 'business_view' ||
				$custom_view == 'technical_view' ||
				$custom_view == 'accountant_view') &&
				!Base_AclCommon::check_permission('Change requirement status')
			)
		)				
			return $status[$v]; 
								
		if($custom_view == 'counselor_view')
		{
			$status_for_change[0] = $status[0];
			$status_for_change[2] = $status[2];
		}				
		else
		{
			$status_for_change = $status;
			if($v >= 3)
			{
				unset($status_for_change[1]);
			//unset($status_for_change[2]);
			}
		}							
				
		SCTV_RequirementCommon::drawLeightboxStatus($prefix, $status_for_change);
		
		if (isset($_REQUEST['form_name']) && $_REQUEST['form_name']==$prefix.'_follow_up_form' && $_REQUEST['id']==$record['id']) 
		{			
			unset($_REQUEST['form_name']);
			
			$v = $_REQUEST['status'];
			$action  = $_REQUEST['action'];
			$note = $_REQUEST['note'];
			$report_employee = $_REQUEST['report_employee'];
			
			if($v == 0)
			{
				$delivery_date = $_REQUEST['delivery_date'];				
				if($delivery_date != null && $delivery_date != '')
				{
					$delivery_date = date('Y-m-d', strtotime($delivery_date));
					Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $record_id, array('status'=>$v, 'delivery_date'=>$delivery_date));
					Utils_RecordBrowserCommon::new_record('SCTV_DeliveryDateHistory', array('requirement'=>$record_id, 'date_time'=>time(), 'employee'=>$report_employee, 'delivery_date'=>$delivery_date, 'note'=>$note));
				}
				else {
					Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $record_id, array('status'=>$v));
				}				
			}	
			elseif($v == 1)
			{
				$deploymentdate = $_REQUEST['deploymentdate'];
				$deploymentdate = date('Y-m-d', strtotime($deploymentdate));						
				$deploymenttime = $_REQUEST['deploymenttime'];
				$acceptancedate = $_REQUEST['acceptancedate'];
				$acceptancedate = date('Y-m-d', strtotime($acceptancedate));
				$deploymentemployee = $_REQUEST['deploymentemployee'];
				$deployment_cable_status = $_REQUEST['deployment_cable_status'];
				if($deployment_cable_status != null)
				{
					$deploymenthd = $_REQUEST['deploymenthd'];
					$deploymentsd = $_REQUEST['deploymentsd'];
				}
				else
				{
					$deploymenthd = 0;
					$deploymentsd = 0;	
				}							
				$deploymentinternetpackage = $_REQUEST['deployment_internet_package'];
				$deploymentbundle = $_REQUEST['deployment_bundle'];
				$deployment_business = $_REQUEST['deployment_business'];
				$cablecontractcode = $_REQUEST['cable_contract_code'];
				$internetcontractcode = $_REQUEST['internet_contract_code'];
				$tapcode = $_REQUEST['tap_code'];
				$lend_wifi = $_REQUEST['lend_wifi'];
												
				// Tang ma so hop dong
				// Cập nhật mã số hợp đồng
				
				Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $record_id, 
					array(
						'status'=>$v,
						'deployment_date'=>$deploymentdate,
						'deployment_time'=>date('Y-m-d') . ' ' . $deploymenttime['__date']['H'].':'.$deploymenttime['__date']['i'] . ':00',
						'acceptance_date'=>$acceptancedate,
						'deployment_cable_status'=>$deployment_cable_status,
						'deployment_employee'=>$deploymentemployee,
						'deployment_hd'=>$deploymenthd,
						'deployment_sd'=>$deploymentsd,
						'deployment_internet_package'=>$deploymentinternetpackage,
						'deployment_bundle'=>$deploymentbundle,
						'deployment_business'=>$deployment_business,						
						'cable_contract_code'=>$cablecontractcode,
						'internet_contract_code'=>$internetcontractcode,
						'bundle_contract_code'=>$bundlecontractcode,
						'tap_code'=>$tapcode,
						'lend_wifi'=>$lend_wifi
					)
				);
				
				$secondary_counselor = $_REQUEST['secondary_counselor'];
				$secondary_hd = $_REQUEST['secondary_hd'];
				$secondary_sd = $_REQUEST['secondary_sd'];
				$secondary_internetpackage = $_REQUEST['secondary_internet_package'];
				
				echo $secondary_counselor;
				if($secondary_counselor != null)
				{
					Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $record_id, 
					array(
						'secondary_counselor'=>$secondary_counselor,
						'secondary_hd'=>$secondary_hd,
						'secondary_sd'=>$secondary_sd,
						'secondary_internet_package'=>$secondary_internetpackage
						)
					);
				}
											
				if ($note) {
					if (get_magic_quotes_gpc())
						$note = stripslashes($note);
					$note = str_replace("\n",'<br />',$note);
					Utils_AttachmentCommon::add('SCTV_Requirement/'.$record_id,0,Acl::get_user(),$note);
				}
				
				Utils_RecordBrowserCommon::new_record('SCTV_StatusHistory', array('requirement'=>$record_id, 'date_time'=>time(), 'employee'=>$deploymentemployee, 'status'=>$v, 'note'=>$note));
			}
			elseif($v == 2)
			{
				Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $record_id, array('status'=>$v));
			}
			else
				Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $record_id, array('status'=>$v));
			
			if($v != 1) // Ghi history cac trang thai khac
			{				
				Utils_RecordBrowserCommon::new_record('SCTV_StatusHistory', array('requirement'=>$record_id, 'date_time'=>time(), 'employee'=>$report_employee, 'status'=>$v, 'note'=>$note));
			}
			
			location(array());			
		}
		$street = SCTV_RequirementCommon::format_address($record['address'], $record['street'], true);
		
		$cable_status = SCTV_RequirementCommon::get_cable_status_name($record['cable_status']);
		
		$internet_package_id = $record['internet_package'];
		if($internet_package_id == null)
			$internet_package = null;
		else
		{
			$internet_package = Utils_RecordBrowserCommon::get_record('SCTV_InternetPackage', $internet_package_id);
			$internet_package = $internet_package->name;	
		}
		
		$bundle_id = $record['bundle'];
 		$bundle_rs = new SCTV_Bundle_Recordset();
		if($bundle_id == null)
			$bundle = null;
		else
		{
			$bundle = $bundle_rs->get_record($bundle_id);
			$bundle = $bundle->name;	
		}
		return '<a href="javascript:void(0)" class="lbOn" rel="'.$prefix.'_followups_leightbox" onMouseDown="'.$prefix.'_set_id('.$record_id.',\''.$record['customer_name'].'\',\''.$street.'\',\''.$record['phone'].'\',\''. $cable_status . '\',\''.$record['number_of_hd'].'\',\''.$record['number_of_sd'].'\',\''.$internet_package.'\',\''.$bundle.'\');">'.$status[$v].'</a>'; 
	}
	public static function display_charge($record, $nolink, $desc) {
		$prefix = 'SCTV_charge_leightbox';
		$record_id = $record['id'];
		$charge = $record[$desc['id']];
		$status = $record['status'];
		
		if (!$charge) $charge = 0;
		
		SCTV_RequirementCommon::drawLeightboxCharge($prefix);
		//print_r($_REQUEST);
		if (isset($_REQUEST['form_name']) && $_REQUEST['form_name']==$prefix.'_follow_up_form' && $_REQUEST['id']==$record['id'] && $_REQUEST['charge'] != $charge) 
		{
			unset($_REQUEST['form_name']);
							
			$new_charge = $_REQUEST['charge'];
			Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $record_id, array('charge'=>$new_charge));		
			
			location(array());
		}
		
		if($status == 0 && Utils_RecordBrowserCommon::get_access('SCTV_Requirement', 'add', $record))
		{
			$street = SCTV_RequirementCommon::format_address($record['address'], $record['street'], true);
		
			$cable_status = SCTV_RequirementCommon::get_cable_status_name($record['cable_status']);
		
			$internet_package_id = $record['internet_package']; 			
			if($internet_package_id == null)
				$internet_package = null;
			else
			{
				$internet_package =Utils_RecordBrowserCommon::get_record('SCTV_InternetPackage', $internet_package_id);
				$internet_package = $internet_package->name;	
			}
		
			$bundle_id = $record['bundle'];
 			$bundle_rs = new SCTV_Bundle_Recordset();
			if($bundle_id == null)
				$bundle = null;
			else
			{
				$bundle = $bundle_rs->get_record($bundle_id);
				$bundle = $bundle->name;	
			}
		
			return '<a href="javascript:void(0)" class="lbOn" rel="'.$prefix.'_followups_leightbox" onMouseDown="'.$prefix.'_set_id('.$record_id.',\''.$record['customer_name'].'\',\''.$street.'\',\''.$record['phone'].'\',\''. $cable_status . '\',\''.$record['number_of_hd'].'\',\''.$record['number_of_sd'].'\',\''.$internet_package.'\',\''.$bundle.'\','.$charge.');">'.($charge==0?__('Charge'):Utils_CurrencyFieldCommon::format($charge)).'</a>';
		}
		else
			return  Utils_CurrencyFieldCommon::format($charge);		
	}
	public static function display_customer_code($record, $nolink, $desc) {
		$prefix = 'SCTV_customer_code_leightbox';
		$record_id = $record['id'];
		$customer_code = $record[$desc['id']];
		$status = $record['status'];	
		
		SCTV_RequirementCommon::drawLeightboxCustomerCode($prefix);

		if (isset($_REQUEST['form_name']) && $_REQUEST['form_name']==$prefix.'_follow_up_form' && $_REQUEST['id']==$record['id']) 
		{
			unset($_REQUEST['form_name']);
							
			$customer_code = $_REQUEST['customer_code'];
			Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $record_id, array('customer_code'=>$customer_code));		
			
			location(array());
		}
		
		if(Utils_RecordBrowserCommon::get_access('SCTV_Requirement', 'add', $record) && $status == 1 && ($customer_code == '' || $customer_code == null))
		{
			$street = SCTV_RequirementCommon::format_address($record['address'], $record['street'], true);
		
			$cable_status = SCTV_RequirementCommon::get_cable_status_name($record['cable_status']);
		
			$internet_package_id = $record['internet_package'];
 			$internet_package_rs = new SCTV_Internetpackage_Recordset();
			if($internet_package_id == null)
				$internet_package = null;
			else
			{
				$internet_package = $internet_package_rs->get_record($internet_package_id);
				$internet_package = $internet_package->name;	
			}
		
			$bundle_id = $record['bundle'];
 			$bundle_rs = new SCTV_Bundle_Recordset();
			if($bundle_id == null)
				$bundle = null;
			else
			{
				$bundle = $bundle_rs->get_record($bundle_id);
				$bundle = $bundle->name;	
			}
		
			return '<a href="javascript:void(0)" class="lbOn" rel="'.$prefix.'_followups_leightbox" onMouseDown="'.$prefix.'_set_id('.$record_id.',\''.$record['customer_name'].'\',\''.$street.'\',\''.$record['phone'].'\',\''. $cable_status . '\',\''.$record['number_of_hd'].'\',\''.$record['number_of_sd'].'\',\''.$internet_package.'\',\''.$bundle.'\');">['. __('Customer Code') . ']</a>';
		}
		else
			return  $customer_code;		
	}
    public static function display_review($record, $nolink, $desc) {
        $checked = $record[$desc['id']];
        if($checked)
            return __('Checked');
        else
        {
            //if(Base_AclCommon::check_permission('Acceptance:Check'))
            {
                $href =  Base_BoxCommon::main_module_instance()->create_confirm_callback_href(_M('Are you sure you want to close #%d requirement?', array($record['id'])), array('SCTV_RequirementCommon', 'update_review'), array('requirement'=>$record['id']));
                return '<a ' . $href . '>' . __('Unchecked') . '</a>';
            }
            //else
              //  return __('Unchecked');
        }
    }
    public static function QFfield_review(&$form, $field, $label, $mode, $default, $desc, $rb_obj){
        if($default)
            $form->addElement('static', $field, $label, __('Checked'));
        else
        {
            //if(Base_AclCommon::check_permission('Acceptance:Check'))
            {
                $href =  Base_BoxCommon::main_module_instance()->create_confirm_callback_href(_M('Are you sure?'), array('SCTV_RequirementCommon', 'update_review'), array('acceptance'=>$rb_obj->record['id']));
                $form->addElement('static', $field, $label, '<a ' . $href . '>' . __('Unchecked') . '</a>');
            }
            //else {
              //  $form->addElement('static', $field, $label, __('Unchecked'));
            //}
        }
    }
    public static function update_review($requirement)
    {
        Utils_RecordBrowserCommon::update_record('SCTV_Requirement', $requirement, array('review'=>true));
    }
	public static function get_requirement_not_scheduled()
	{
		$recs = Utils_RecordBrowserCommon::get_records('SCTV_Requirement');
		$options = array();
		foreach ($recs as $key => $value) {
			$options[$value['id']] = '#' . $value['id'] . '[' . $value['customer_name'] . ']';
		}
		
		return $options;
	}

	public static function get_requirement_by_area($date, $area, $i_am_admin, $manager = null)
	{		
		if($area == null){
			$recs = DB::Execute("
				select sctv_requirement_data_1.id, f_customer_name, f_address, sctv_street_data_1.f_name as street_name, sctv_area_data_1.f_name as area_name, sctv_requirement_data_1.f_phone,
						sctv_requirement_data_1.f_cable_status, sctv_requirement_data_1.f_main_analog, sctv_requirement_data_1.f_sub_analog, sctv_requirement_data_1.f_number_of_hd, sctv_requirement_data_1.f_number_of_sd, sctv_internetpackage_data_1.f_name as internet_package, sctv_bundle_data_1.f_name as bundle,
						case when sctv_deliverydatehistory_data_1.f_note is not null then sctv_deliverydatehistory_data_1.f_note else sctv_requirement_data_1.f_note end as f_note
				from sctv_requirement_data_1
				join sctv_street_data_1 on sctv_street_data_1.id = sctv_requirement_data_1.f_street
				left join sctv_area_data_1 on ((sctv_requirement_data_1.f_manager_area is null and sctv_area_data_1.id = sctv_street_data_1.f_area) or sctv_area_data_1.id = sctv_requirement_data_1.f_manager_area)
				left join sctv_internetpackage_data_1 on sctv_internetpackage_data_1.id = sctv_requirement_data_1.f_internet_package
				left join sctv_bundle_data_1 on sctv_bundle_data_1.id = sctv_requirement_data_1.f_bundle
				left join sctv_deliverydatehistory_data_1 on sctv_deliverydatehistory_data_1.active = 1 and sctv_deliverydatehistory_data_1.f_requirement = sctv_requirement_data_1.id and sctv_deliverydatehistory_data_1.f_delivery_date = sctv_requirement_data_1.f_delivery_date
				where sctv_requirement_data_1.active = 1 and sctv_requirement_data_1.f_status = '0' and sctv_requirement_data_1.f_delivery_date <= %D 
				and 
				 	not exists
					(
						select *
						from sctv_deployment_data_1
						where sctv_deployment_data_1.f_requirement = sctv_requirement_data_1.id and
							sctv_deployment_data_1.active = 1 and
							sctv_deployment_data_1.f_date = %T				
					)
					and
					(
						(true = %b) or
						(
							sctv_requirement_data_1.f_manager_area is null and
							sctv_street_data_1.f_area in
							(
								select id
								from sctv_area_data_1
								where sctv_area_data_1.active = 1 and sctv_area_data_1.f_manager = %d 
							)
						)
						or
						(
							sctv_requirement_data_1.f_manager_area in
							(
								select id
								from sctv_area_data_1
								where sctv_area_data_1.active = 1 and sctv_area_data_1.f_manager = %d 
							)
						)
					)			
				", array($date, $date, $i_am_admin, $manager, $manager));
		}
		else {
			$recs = DB::Execute("
				select sctv_requirement_data_1.id, f_customer_name, f_address, sctv_street_data_1.f_name as street_name, sctv_area_data_1.f_name as area_name, sctv_requirement_data_1.f_phone,
						sctv_requirement_data_1.f_cable_status, sctv_requirement_data_1.f_main_analog, sctv_requirement_data_1.f_sub_analog, sctv_requirement_data_1.f_number_of_hd, sctv_requirement_data_1.f_number_of_sd, sctv_internetpackage_data_1.f_name as internet_package, sctv_bundle_data_1.f_name as bundle,
						case when sctv_deliverydatehistory_data_1.f_note is not null then sctv_deliverydatehistory_data_1.f_note else sctv_requirement_data_1.f_note end as f_note
				from sctv_requirement_data_1
				left join sctv_street_data_1 on sctv_street_data_1.id = sctv_requirement_data_1.f_street
				left join sctv_area_data_1 on ((sctv_requirement_data_1.f_manager_area is null and sctv_area_data_1.id = sctv_street_data_1.f_area) or sctv_area_data_1.id = sctv_requirement_data_1.f_manager_area)
				left join sctv_internetpackage_data_1 on sctv_internetpackage_data_1.id = sctv_requirement_data_1.f_internet_package
				left join sctv_bundle_data_1 on sctv_bundle_data_1.id = sctv_requirement_data_1.f_bundle
				left join sctv_deliverydatehistory_data_1 on sctv_deliverydatehistory_data_1.active = 1 and sctv_deliverydatehistory_data_1.f_requirement = sctv_requirement_data_1.id and sctv_deliverydatehistory_data_1.f_delivery_date = sctv_requirement_data_1.f_delivery_date
				where sctv_requirement_data_1.active = 1 and sctv_requirement_data_1.f_status = '0' and sctv_requirement_data_1.f_delivery_date <= %D and
					((sctv_requirement_data_1.f_manager_area is null and sctv_street_data_1.f_area = %d) or sctv_requirement_data_1.f_manager_area = %d)  
				and 
				 	not exists
					(
						select *
						from sctv_deployment_data_1
						where sctv_deployment_data_1.f_requirement = sctv_requirement_data_1.id and
							sctv_deployment_data_1.active = 1 and
							sctv_deployment_data_1.f_date = %T				
					)			
				", array($date, $area, $area, $date));			
		}
										
		$options = array();
		foreach ($recs as $key => $value) {
			$services = SCTV_RequirementCommon::get_cable_status_name($value['f_cable_status']);
			if($value['f_number_of_hd'] > 0) $services .= ' ' . $value['f_number_of_hd'] . 'HD';
			if($value['f_number_of_sd'] > 0) $services .= ' ' . $value['f_number_of_sd'] . 'SD';
            if($value['f_main_analog'] > 0) $services .= ' ' . $value['f_main_analog'] . 'MAL';
            if($value['f_sub_analog'] > 0) $services .= ' ' . $value['f_sub_analog'] . 'SAL';
			if($value['internet_package'] != NULL) $services .= ' Net:' . $value['internet_package'];
			if($value['bundle'] != NULL) $services .= ' Trọn gói:' . $value['bundle']; 
			$options[$value['id']] = '#' . $value['id'] . ' ' . $value['f_customer_name'] . '(' . $value['f_address'] . ' ' . $value['street_name'] . '[' . $value['area_name'] . ']'. ', ĐT: ' . $value['f_phone'] . ')(' . $services . ') '. $value['f_note'];
		}
		
		return $options;
	
	}
	
	public static function get_requirement_statictis_area($date, $i_am_admin, $manager)
	{
		$recs = DB::Execute('
			select sctv_area_data_1.f_name, count(sctv_requirement_data_1.id) as planned, count(sctv_deployment_data_1.id) as assigned 
			from sctv_requirement_data_1
			left join sctv_street_data_1 on sctv_street_data_1.id = sctv_requirement_data_1.f_street
			join sctv_area_data_1 on ((sctv_requirement_data_1.f_manager_area is null and sctv_area_data_1.id = sctv_street_data_1.f_area) or sctv_area_data_1.id = sctv_requirement_data_1.f_manager_area) and (true = %b or sctv_area_data_1.f_manager = %d)
			left join sctv_deployment_data_1 on sctv_deployment_data_1.active = 1 and sctv_deployment_data_1.f_requirement = sctv_requirement_data_1.id and sctv_deployment_data_1.f_date = %T   
			where sctv_requirement_data_1.active = 1 and sctv_requirement_data_1.f_delivery_date <= %T and sctv_requirement_data_1.f_status = %d
			group by sctv_area_data_1.f_name
		',
		array($i_am_admin, $manager, $date, $date, 0));
		
		return $recs;
	}
	public static function get_requirement_statictis_technical($date, $i_am_admin, $manager)
	{		
		$recs = DB::Execute("
			select A.id, contact_data_1.f_last_name || ' ' || contact_data_1.f_first_name as fullname, sum(assigned) as assigned, sum(completed) as completed 
			from 
			(
				select contact_data_1.id, count(sctv_deployment_data_1.id) as assigned, 0 as completed
				from contact_data_1
				left join sctv_deployment_data_1 on sctv_deployment_data_1.active = 1 and sctv_deployment_data_1.f_date = %T and contact_data_1.id = sctv_deployment_data_1.f_technical 
				where contact_data_1.active = 1 and ((true = %b and contact_data_1.f_group like %s) or contact_data_1.f_manager = %d)
				group by contact_data_1.id
				
				union all
				
				select contact_data_1.id, 0 as assigned, 1 as completed 
				from sctv_requirement_data_1
				join contact_data_1 on contact_data_1.active = 1 and contact_data_1.id = sctv_requirement_data_1.f_deployment_employee and (true = %b or contact_data_1.f_manager = %d)
				where sctv_requirement_data_1.active = 1 and sctv_requirement_data_1.f_deployment_date = %T
			) A
			join contact_data_1 on contact_data_1.id = A.id		
			group by A.id, contact_data_1.f_last_name, contact_data_1.f_first_name
			order by assigned desc, completed desc
		",
		array($date, $i_am_admin, '%Technical%', $manager, $i_am_admin, $manager, $date));
		
		return $recs;
	}
	public static function get_requirements_by_technical($date, $employee, $manager, $i_am_admin)
	{
		$quangninh_id = SCTV_RequirementCommon::get_quangninh_id();
		if($employee == null)
		{
			$recs = DB::Execute("select * from sctv_requirements_assigned_all(%d, %T, %d, %b)", array($quangninh_id, $date, $manager, $i_am_admin));
		}
		else
		{
			$recs = DB::Execute("select * from sctv_requirements_assigned_technical(%d, %T, %d)", array($quangninh_id, $date, $employee));
		}
				
		return $recs;
	}
	public static function format_address($address, $street_id, $nolink)
	{
 		return $address . " " . self::format_street($street_id, $nolink); 		
	}
	public static function format_street($street_id, $nolink)
	{
 		$street = Utils_RecordBrowserCommon::get_record('SCTV_Street',$street_id); 
			
		$area = Utils_RecordBrowserCommon::get_record('SCTV_Area',$street['area']);		
				
		if($nolink)
		{
			return $street['name'] . '[' . $area['name'] .']';					
		}
		else
		{
			$street_link = Utils_RecordBrowserCommon::record_link_open_tag('SCTV_Street', $street['id'], $nolink).$street['name'].Utils_RecordBrowserCommon::record_link_close_tag();		
 			$area_link = Utils_RecordBrowserCommon::record_link_open_tag('SCTV_Area', $area['id'], $nolink).$area['name'].Utils_RecordBrowserCommon::record_link_close_tag();
 
 			return $street_link . "[" . $area_link . "]";
		} 		
	}
	
	public static function check_location() {
		if (isset($_REQUEST['__location']) && self::$last_location!=$_REQUEST['__location']) {
			self::$last_location = $_REQUEST['__location'];
			self::$leightbox_ready = array();	
		}
	}
	public static function drawLeightboxStatus($prefix, $status) {
		if(MOBILE_DEVICE) return;
		self::check_location();
		if (!isset(self::$leightbox_ready[$prefix])) {
			self::$leightbox_ready[$prefix] = true;

			$theme = Base_ThemeCommon::init_smarty();
			eval_js_once($prefix.'_followups_deactivate = function(){leightbox_deactivate(\''.$prefix.'_followups_leightbox\');}');
	
			$required_error = __('Required');
			$required_error .= Libs_QuickFormCommon::get_error_closing_button();
			
			$invalid_error = __('invalid');
			$invalid_error .= Libs_QuickFormCommon::get_error_closing_button();
			
			eval_js('check_if_'.$prefix.'_set_deploymentdate = function() {
					status=$(\''.$prefix.'_status\').value;
					is_completed = status == 1;
					deploymentdate = $(\''.$prefix.'_deploymentdate\').value;
					deployment_cable_status = $(\''.$prefix.'_deployment_cable_status\').value;
					cablecontractcode = $(\''.$prefix.'_cablecontractcode\').value;
										
					if(is_completed)
					{
						ok = true;
						 
						if(!deploymentdate)
						{
							$(\''.$prefix.'_deploymentdate_required\').innerHTML=\''.Epesi::escapeJS($required_error).'\';
							ok = false;							
						}
						else {
							$(\''.$prefix.'_deploymentdate_required\').innerHTML=\'\';
														
							var parts = deploymentdate.split("-");
							date1 = new Date(parts[2], parts[1]-1, parts[0]);
							
							acceptance_date = $(\''.$prefix.'_acceptancedate\').value;
							var parts = acceptance_date.split("-");
							date2 = new Date(parts[2], parts[1]-1, parts[0]);
							if(date1 > date2) 
							{
								$(\''.$prefix.'_acceptancedate_invalid\').innerHTML=\''.Epesi::escapeJS($invalid_error).'\';
								ok = false;
							}
							else {
								$(\''.$prefix.'_acceptancedate_invalid\').innerHTML=\'\';
							}
						}
						
						var deploymentemployee_select = $(\'deploymentemployee\');
						if(deploymentemployee_select == null || deploymentemployee_select.value == \'\')
						{
							$(\''.$prefix.'_deploymentemployee_required\').innerHTML=\''.Epesi::escapeJS($required_error).'\';
							ok = false;							
						}
						else {
							$(\''.$prefix.'_deploymentemployee_required\').innerHTML=\'\';
						}

						if(deployment_cable_status != "" && !cablecontractcode)
						{
							$(\''.$prefix.'_cablecontractcode_required\').innerHTML=\''.Epesi::escapeJS($required_error).'\';
							ok = false;							
						}
						else
						{
							$(\''.$prefix.'_cablecontractcode_required\').innerHTML=\'\';
						}
						
						internetcontractcode = $(\''.$prefix.'_internet_contract_code\').value;
						deployment_internet_package = $(\''.$prefix.'_deployment_internet_package\').value;
						if(deployment_internet_package != "" && !internetcontractcode)
						{
							$(\''.$prefix.'_deploymentinternetcontractcode_required\').innerHTML=\''.Epesi::escapeJS($required_error).'\';
							ok = false;
						}
						else {
							$(\''.$prefix.'_deploymentinternetcontractcode_required\').innerHTML=\'\';
						}

						var deployment_internet_package_text = jQuery("#'.$prefix.'_deployment_internet_package option:selected").text();
						
						if(deployment_internet_package != "" && !/^[a-zA-Z]+$/.test(deployment_internet_package_text) && !$("'.$prefix.'_deployment_bundle").value)
						{
							$(\''.$prefix.'_deploymentbundle_required\').innerHTML=\''.Epesi::escapeJS($required_error).'\';
							ok = false;
						}
						else {
							$(\''.$prefix.'_deploymentbundle_required\').innerHTML=\'\';
						}
						
						if(deployment_cable_status != "")
						{
							deploymenthd = $(\''.$prefix.'_deploymenthd\').value;
							deploymentsd = $(\''.$prefix.'_deploymentsd\').value;
							
							if(!isNaN(deploymenthd) && !isNaN(deploymentsd))
							{
								if(deploymenthd <= 0 && deploymentsd <= 0)
								{
									$(\''.$prefix.'_deploymenthd_invalid\').innerHTML=\''.Epesi::escapeJS($invalid_error).'\';
									ok = false;	
								}
								else								
									$(\''.$prefix.'_deploymenthd_invalid\').innerHTML=\'\';
							}
							else
							{
								if(isNaN(deploymenthd))
								{
									$(\''.$prefix.'_deploymenthd_invalid\').innerHTML=\''.Epesi::escapeJS($invalid_error).'\';
									ok = false;	
								}
								else {
									$(\''.$prefix.'_deploymenthd_invalid\').innerHTML=\'\';	
								}									
								
								if(isNaN(deploymentsd))
								{
									$(\''.$prefix.'_deploymentsd_invalid\').innerHTML=\''.Epesi::escapeJS($invalid_error).'\';
									ok = false;
								}
								else {
									$(\''.$prefix.'_deploymentsd_invalid\').innerHTML=\'\';
								}
							}																																																
						}
						else
						{
							$(\''.$prefix.'_deploymenthd_invalid\').innerHTML=\'\';
						}

						return ok;
					}					
					else {
						var report_employee_select = $(\'report_employee\');
						
						if(report_employee_select == null || report_employee_select.value == \'\')
						{
							$(\''.$prefix.'_report_employee_required\').innerHTML=\''.Epesi::escapeJS($required_error).'\';
							return false;	
						}							
						else
						{
							$(\''.$prefix.'_report_employee_required\').innerHTML=\'\';							
							return true;
						}									
					}
				}
			');
			
			$theme->assign('form_requirement_code', array('label'=>__('Requirement Code')));
			$theme->assign('form_customer_name', array('label'=>__('Customer Name')));
			$theme->assign('form_street', array('label'=>__('Address')));
			$theme->assign('form_phone', array('label'=>__('Phone')));
			$theme->assign('form_cable_status', array('label'=>__('Cable Status')));
			$theme->assign('form_internetpackage', array('label'=>__('Internet Package')));
			$theme->assign('form_bundle', array('label'=>__('Bundle')));
			
			$theme->assign('report_employee_required_error','<div id="'.$prefix.'_report_employee_required" class="form_error"></div>');
			$theme->assign('deploymentdate_required_error','<div id="'.$prefix.'_deploymentdate_required" class="form_error"></div>');
			$theme->assign('acceptancedate_invalid_error','<div id="'.$prefix.'_acceptancedate_invalid" class="form_error"></div>');			
			$theme->assign('deploymentemployee_required_error','<div id="'.$prefix.'_deploymentemployee_required" class="form_error"></div>');
			$theme->assign('deploymenthd_invalid_error','<div id="'.$prefix.'_deploymenthd_invalid" class="form_error"></div>');
			$theme->assign('deploymentsd_invalid_error','<div id="'.$prefix.'_deploymentsd_invalid" class="form_error"></div>');
			$theme->assign('deploymentbundle_required_error','<div id="'.$prefix.'_deploymentbundle_required" class="form_error"></div>');			
			$theme->assign('cablecontractcode_required_error','<div id="'.$prefix.'_cablecontractcode_required" class="form_error"></div>');
			$theme->assign('deploymentinternetcontractcode_required_error','<div id="'.$prefix.'_deploymentinternetcontractcode_required" class="form_error"></div>');
	
			eval_js($prefix.'_submit_form = function () {'.
						'$(\''.$prefix.'_follow_up_form\').submited.value=1;Epesi.href($(\''.$prefix.'_follow_up_form\').serialize(), \'processing...\');$(\''.$prefix.'_follow_up_form\').submited.value=0;'.
					'}');
			eval_js($prefix.'_set_action = function (arg) {'.
						'document.forms["'.$prefix.'_follow_up_form"].action.value = arg;'.
					'}');
			eval_js($prefix.'_set_id = function (id, name, street, phone, cable_status, hd, sd, internetpackage, bundle) {'.
						'document.forms["'.$prefix.'_follow_up_form"].id.value = id;'.
						'$("form_requirement_code").innerHTML ="#"+id;'.											
						'$("form_customer_name").innerHTML =name;'.
						'$("form_street").innerHTML=street;'.
						'$("form_phone").innerHTML=phone;'.
						'$("form_cable_staus").innerHTML=cable_status;'.
						'$("form_hd").innerHTML=hd;'.
						'$("form_sd").innerHTML=sd;'.
						'$("form_internetpackage").innerHTML=internetpackage;'.
						'$("form_bundle").innerHTML=bundle;'.
						'$("'.$prefix.'_status").value = "";'.
						'$("'.$prefix.'_delivery_date").value = "";'.					
						'$("'.$prefix.'_deploymentdate").value = "";'.
						//'$("#deploymenttime[__date][H]").value = "5";'.
						//'$("#deploymenttime[__date][i]").value = "5";'.
						'$("'.$prefix.'_acceptancedate").value = "";'.						
						//'$("'.$prefix.'_deployment_employee").value = "";'.
						//'$("'.$prefix.'_report_employee").value = "";'.
						'$("'.$prefix.'_deployment_cable_status").value = "";'.
						'$("'.$prefix.'_deploymenthd").value = "";'.				
						'$("'.$prefix.'_deploymentsd").value = "";'.
						'$("'.$prefix.'_deployment_internet_package").value = "";'.
						'$("'.$prefix.'_deployment_bundle").value = "";'.
						'$("'.$prefix.'_cablecontractcode").value = "";'.
						'$("'.$prefix.'_internet_contract_code").value = "";'.
						'$("'.$prefix.'_tap_code").value = "";'.
						'$("'.$prefix.'_note").value="";'.						
						'document.getElementById(\'SCTV_Completed\').style.display  = \'none\';'.
					'}');
			
			eval_js($prefix.'_make_business = function(){'
				. ' var deployment_cable_status = $("'.$prefix.'_deployment_cable_status").value;'
				. ' var cablecontractcode_element = jQuery("#'.$prefix.'_cablecontractcode");'
				. ' var internetcontractcode_element = jQuery("#'.$prefix.'_internet_contract_code");'
				. ' var deployment_hd_element = jQuery("#'.$prefix.'_deploymenthd");'
				. ' var deployment_sd_element = jQuery("#'.$prefix.'_deploymentsd");'
				. ' var deployment_internet_package = $("'.$prefix.'_deployment_internet_package").value;'
				. ' var deployment_internet_package_text = jQuery("#'.$prefix.'_deployment_internet_package option:selected").text();'
				. ' var deployment_bundle_element = jQuery("#'.$prefix.'_deployment_bundle");'
                . ' var deployment_bundle = $("'.$prefix.'_deployment_bundle").value;'
                . ' var deployment_bundle_text = jQuery("#'.$prefix.'_deployment_bundle option:selected").text();'
				. ' var business = "";'
				. '
					if(deployment_cable_status == "")
					{
						deployment_hd_element.prop("disabled","disabled");						
						deployment_hd_element.prop("value","0");			
						deployment_sd_element.prop("disabled","disabled");
						deployment_sd_element.prop("value","0");
						
						cablecontractcode_element.prop("disabled", "disabled");
						cablecontractcode_element.prop("value", "");						
						
						if(deployment_internet_package == "")
						{
							internetcontractcode_element.prop("disabled","disabled");
							internetcontractcode_element.prop("value", "");
							deployment_bundle_element.removeAttr("disabled");

                            /*var deployment_bundle = $("'.$prefix.'_deployment_bundle").value;
                            var deployment_bundle_text = jQuery("#'.$prefix.'_deployment_bundle option:selected").text();
							if(deployment_bundle == "")
							{
							}
							else
							{
								business = "Chuyển trọn gói " + deployment_bundle_text;								
							}*/
						}
						else
						{
							internetcontractcode_element.removeAttr("disabled");
							
							if(/^[a-zA-Z]+$/.test(deployment_internet_package_text))
							{
								deployment_bundle_element.prop("disabled","disabled");
								deployment_bundle_element.prop("value", "");
							}
							else {
								deployment_bundle_element.removeAttr("disabled");
							}

                            /*var deployment_bundle = $("'.$prefix.'_deployment_bundle").value;
                            var deployment_bundle_text = jQuery("#'.$prefix.'_deployment_bundle option:selected").text();
							if(deployment_bundle == "")
							{
								business = "Lắp mới Internet";													
							}
							else
							{
								business = "Lắp mới Internet" + " chuyển trọn gói " + deployment_bundle_text;								
							}*/
						}
					}
					else if(deployment_cable_status == 1)
					{
						deployment_hd_element.removeAttr("disabled");
						deployment_sd_element.removeAttr("disabled");
						
						cablecontractcode_element.removeAttr("disabled");
						
						if(deployment_internet_package == "")
						{
							internetcontractcode_element.prop("disabled","disabled");
							internetcontractcode_element.prop("value", "");
							deployment_bundle_element.removeAttr("disabled");

                            /*var deployment_bundle = $("'.$prefix.'_deployment_bundle").value;
                            var deployment_bundle_text = jQuery("#'.$prefix.'_deployment_bundle option:selected").text();
							if(deployment_bundle == "")
							{
								business = "Lắp mới THC";						
							}
							else
							{
								business = "Lắp mới THC" + " chuyển trọn gói " + deployment_bundle_text;
							}*/
						}
						else
						{
							internetcontractcode_element.removeAttr("disabled");
							
							if(/^[a-zA-Z]+$/.test(deployment_internet_package_text))
							{
								deployment_bundle_element.prop("disabled","disabled");
								deployment_bundle_element.prop("value", "");
							}
							else {
								deployment_bundle_element.removeAttr("disabled");
							}

							/*var deployment_bundle = $("'.$prefix.'_deployment_bundle").value;
                            var deployment_bundle_text = jQuery("#'.$prefix.'_deployment_bundle option:selected").text();
							if(deployment_bundle == "")
							{
								business = "Lắp mới THC và Internet";															
							}	
							else
							{
								business = "Lắp mới trọn gói " + deployment_bundle_text;
							}*/
						}
					}
					else if(deployment_cable_status == 0)
					{
						deployment_hd_element.removeAttr("disabled");
						deployment_sd_element.removeAttr("disabled");
						
						cablecontractcode_element.removeAttr("disabled");
						
						if(deployment_internet_package == "")
						{
							internetcontractcode_element.prop("disabled","disabled");
							internetcontractcode_element.prop("value", "");
							deployment_bundle_element.removeAttr("disabled");

                            /*var deployment_bundle = $("'.$prefix.'_deployment_bundle").value;
                            var deployment_bundle_text = jQuery("#'.$prefix.'_deployment_bundle option:selected").text();
							if(deployment_bundle == "")
							{
								business = "Lắp thêm THC";						
							}
							else
							{
								business = "Lắp thêm THC chuyển trọn gói " + deployment_bundle_text;
							}*/
						}
						else
						{
							internetcontractcode_element.removeAttr("disabled");
							
							if(/^[a-zA-Z]+$/.test(deployment_internet_package_text))
							{
								deployment_bundle_element.prop("disabled","disabled");
								deployment_bundle_element.prop("value", "");
							}
							else {
								deployment_bundle_element.removeAttr("disabled");
							}

                            /*var deployment_bundle = $("'.$prefix.'_deployment_bundle").value;
                            var deployment_bundle_text = jQuery("#'.$prefix.'_deployment_bundle option:selected").text();
							if(deployment_bundle == "")
							{
								business = "Lắp thêm THC và lắp mới Internet";															
							}	
							else
							{
								business = "Lắp thêm THC và lắp mới Internet chuyển trọn gói " + deployment_bundle_text;
							}*/
						}
					}
				'
				. ' $("'.$prefix.'_deployment_business").value = business;'
                . ' var deployment_bundle = $("'.$prefix.'_deployment_bundle").value;'
                . ' var deployment_bundle_text = jQuery("#'.$prefix.'_deployment_bundle option:selected").text();'
                . ' new Ajax.Request("modules/SCTV/Requirement/deployment_business.php",
                	{
                		method:"post",
                		parameters:{
                		    deployment_cable_status:deployment_cable_status,
                		    deployment_internet_package:deployment_internet_package,
                		    deployment_bundle:deployment_bundle,
                		    deployment_bundle_text:deployment_bundle_text
                		},
                	 	onSuccess: function(t) {
                	 	    //alert(t.responseText);
                	 	    $("'.$prefix.'_deployment_business").value = t.responseText;
                	 	}});'
                . '}'
			);
							
			
			$theme->assign('form_open','<form id="'.$prefix.'_follow_up_form" name="'.$prefix.'_follow_up_form" method="POST">'.
							'<input type="hidden" name="submited" value="0" />'.
							'<input type="hidden" name="form_name" value="'.$prefix.'_follow_up_form" />'.
							'<input type="hidden" name="id" value="" />'.
							'<input type="hidden" name="action" value="" />');		
							
			$status_html = '<select name="status" value="0" id="'.$prefix.'_status" onChange="
				var completed = document.getElementById(\'SCTV_Completed\');
				var other = document.getElementById(\'SCTV_Other\');
				var delivery_date = document.getElementById(\'SCTV_delivery_date\');
				if(completed != null && other != null)
				{
					var status = this.options[this.selectedIndex].value; 
					if(status == 1)
					{
						completed.style.display  = \'table\';
						other.style.display  = \'none\';
						delivery_date.style.display  = \'none\';
					}
					else
					{
						completed.style.display  = \'none\';
						other.style.display  = \'table\';
						if(status == 0) delivery_date.style.display  = \'table\';
					}						
				}';
			
			$status_html .= '"><option value="">---</option>';
			
			foreach ($status as $k=>$w)
				$status_html .= '<option value="'.$k.'">'.$w.'</option>';
			$status_html .= '</select>';
			
			$theme->assign('form_status',	array(
							'label'=>__('Status'),							
							'html'=>$status_html));
							
			$report_employee = HTML_QuickForm::createElement('autoselect', 'report_employee', _M('Report Employee'), array(), array(array('CRM_ContactsCommon','autoselect_contact_suggestbox'), array(array(), array('param'=>'Last Name|First Name'), array('CRM_ContactsCommon', 'contact_format_default'))), array('CRM_ContactsCommon', 'contact_format_default'), array('id'=>$prefix.'_report_employee'));
			$custom_view = Module::static_get_module_variable('SCTV_Requirement', 'custom_view', null);
			if($custom_view == 'counselor_view')
			{
				$my_contact =  CRM_ContactsCommon::get_my_record();
				$report_employee->setValue($my_contact['id']);
				//$report_employee->setAttribute('hidden')
				eval_js('var other = document.getElementById(\'SCTV_Other\');other.style.visibility=\'hidden\';');
			}				
			$theme->assign('form_report_employee', array(
							'label'=>__('Report Employee'),
							'html'=>$report_employee->toHtml()										
							));
			
			$delivery_date = HTML_QuickForm::createElement(
				'datepicker', 
				'delivery_date', 
				_M('Delivery Date'), 
				array(
					'id'=>$prefix.'_delivery_date'
				)
			);
			
			$theme->assign('form_delivery_date', array(
						'label'=>__('Delivery Date'),
						'html'=>$delivery_date->toHtml()										
							));
															
			$deploymentemployee = HTML_QuickForm::createElement('autoselect', 'deploymentemployee', _M('Employee'), array(), array(array('CRM_ContactsCommon','autoselect_contact_suggestbox'), array(array('group'=>'Technical'), array('param'=>'Last Name|First Name'), array('CRM_ContactsCommon', 'contact_format_default'))), array('CRM_ContactsCommon', 'contact_format_default'), array('id'=>$prefix.'_deployment_employee'));			
			$theme->assign('form_deploymentemployee', array(
							'label'=>__('Deployment Employee'),
							'html'=>$deploymentemployee->toHtml()										
							));
											
			$deploymentdate = HTML_QuickForm::createElement(
				'datepicker', 
				'deploymentdate', 
				_M('Deployment Date'), 
				array(
					'id'=>$prefix.'_deploymentdate',
					'onchange'=>'						
						var deploymentdate = $(\''.$prefix.'_deploymentdate\').value;
						var acceptance_date = $(\''.$prefix.'_acceptancedate\').value;
						if(deploymentdate && !acceptance_date)  
						{
							$(\''.$prefix.'_acceptancedate\').value = deploymentdate;
						}																							
						'
											
					. 'new Ajax.Request(\'modules/SCTV/Requirement/server_hour.php\','
                	. '{ method: \'get\', '
                	. 'onComplete: function(t) {'
                	. 'jQuery("select[name=\'deploymenttime[__date][H]\'] option").filter(function() {return this.value == t.responseText; }).attr(\'selected\', true);'
                	. '}});'
                	
                	. 'new Ajax.Request(\'modules/SCTV/Requirement/server_minute.php\','
                	. '{ method: \'get\', '
                	. 'onComplete: function(t) {'
                	. 'jQuery("select[name=\'deploymenttime[__date][i]\'] option").filter(function() {return this.text == t.responseText; }).attr(\'selected\', true);'
                	. '}})'
				)
			);
			
			$theme->assign('form_deploymentdate', array(
						'label'=>__('Deployment Date'),
						'html'=>$deploymentdate->toHtml()										
							));

			$time_format = Base_RegionalSettingsCommon::time_12h() ? 'h:i a' : 'H:i'; 			
			$deploymenttime = HTML_QuickForm::createElement('timestamp', 'deploymenttime', _M('Deployment Time'), array('id'=>$prefix.'_deploymenttime', 'date'=>false, 'format'=>$time_format, 'optionIncrement'=>array('i' => 1, 's' => 1)));
			$theme->assign('form_deploymenttime', array(
							'label'=>__('Deployment Time'),
							'html'=>$deploymenttime->toHtml()										
							));
			
			$acceptancedate = HTML_QuickForm::createElement(
				'datepicker', 
				'acceptancedate', 
				_M('Acceptance Date'), 
				array(
					'id'=>$prefix.'_acceptancedate'
				)
			);
			
			$theme->assign('form_acceptancedate', array(
						'label'=>__('Acceptance Date'),
						'html'=>$acceptancedate->toHtml()										
							));
							
			$deployment_cable_status = HTML_QuickForm::createElement('select', 'deployment_cable_status', _M('Deployment cable status'), array(''=>'---','1'=>__('New cable'), '0'=>__('Addition cable')), 
				array(
					'id'=>$prefix.'_deployment_cable_status',
					'onchange'=>$prefix.'_make_business();'					                
				)
			);
			$theme->assign('form_deployment_cable_status', array(
						'label'=>__('Deployment Cable Status'),
						'html'=>$deployment_cable_status->toHtml()										
							));
															
							
			$deploymenthd = HTML_QuickForm::createElement('text', 'deploymenthd', _M('Deployment HD'), array('id'=>$prefix.'_deploymenthd', 'disabled'=>'disabled')); 
			$theme->assign('form_deploymenthd', array(
							'label'=>__('Deployment HD'),
							'html'=>$deploymenthd->toHtml()										
							));
			
			$deploymentsd = HTML_QuickForm::createElement('text', 'deploymentsd', _M('Deployment SD'), array('id'=>$prefix.'_deploymentsd', 'disabled'=>'disabled'));
			$theme->assign('form_deploymentsd', array(
							'label'=>__('Deployment SD'),
							'html'=>$deploymentsd->toHtml()										
							));
			
			$internetpackages = DB::GetAssoc('SELECT id, f_name FROM sctv_internetpackage_data_1 where active = 1');
			foreach ($internetpackages as $k=>$u)
				$internetpackages[$k] = $u;
			asort($internetpackages);
			$internetpackages = array(''=>'---')+$internetpackages;
					
			$deploymentinternetpackage = HTML_QuickForm::createElement('select', 'deployment_internet_package', __('Deployment Internet Package'), $internetpackages, 
				array(
					'id'=>$prefix.'_deployment_internet_package',
					'onchange'=>$prefix.'_make_business();'
				)
			);
			$theme->assign('form_deploymentinternetpackage', array(
							'label'=>__('Internet Package'),
							'html'=>$deploymentinternetpackage->toHtml()										
							));
			
			$bundle = DB::GetAssoc('SELECT id, f_name FROM sctv_bundle_data_1 where active = 1');
			foreach ($bundle as $k=>$u)
				$bundle[$k] = $u;
			asort($bundle);
			$bundle = array(''=>'---')+$bundle;		
			$deploymentbundle = HTML_QuickForm::createElement('select', 'deployment_bundle', __('Deployment Bundle'), $bundle, 
				array(
					'id'=>$prefix.'_deployment_bundle',
					'onchange'=>$prefix.'_make_business();'
				)
			);
			$theme->assign('form_deploymentbundle', array(
							'label'=>__('Bundle'),
							'html'=>$deploymentbundle->toHtml()										
							));										
						
			$deployment_business = HTML_QuickForm::createElement('text', 'deployment_business', 'Deployment Business', array('id'=>$prefix.'_deployment_business', 'readonly'=>true));
			$theme->assign('form_deployment_business', array(
							'label'=>__('Deployment Business'),
							'html'=>$deployment_business->toHtml()										
							));
							
			$deploymentcablecontractcode = HTML_QuickForm::createElement('text', 'cable_contract_code', 'Cable Contract Code', array('id'=>$prefix.'_cablecontractcode', 'disabled'=>'disabled'));
			$theme->assign('form_deploymentcablecontractcode', array(
							'label'=>__('Cable Contract Code'),
							'html'=>$deploymentcablecontractcode->toHtml()										
							));
							
			$deploymentinternetcontractcode = HTML_QuickForm::createElement('text', 'internet_contract_code', 'Internet Contract Code', array('id'=>$prefix.'_internet_contract_code', 'disabled'=>'disabled'));
			$theme->assign('form_deploymentinternetcontractcode', array(
							'label'=>__('Internet Contract Code'),
							'html'=>$deploymentinternetcontractcode->toHtml()										
							));							
					
			
			$deploymenttapcode = HTML_QuickForm::createElement('text', 'tap_code', 'Tap Code', array('id'=>$prefix.'_tap_code'));
			$theme->assign('form_deploymenttapcode', array(
							'label'=>__('Tap Code'),
							'html'=>$deploymenttapcode->toHtml()										
							));
							
			$lend_wifi = HTML_QuickForm::createElement('checkbox', 'lend_wifi', '', array('id'=>$prefix.'_lend_wifi'));
			$theme->assign('form_lend_wifi', array(
							'label'=>__('Lend Wifi'),
							'html'=>$lend_wifi->toHtml()										
							));
							
			$secondary_counselor = HTML_QuickForm::createElement('autoselect', 'secondary_counselor', _M('Secondary Counselor'), array(), array(array('CRM_ContactsCommon','autoselect_contact_suggestbox'), array(array(), array('param'=>'Last Name|First Name'), array('CRM_ContactsCommon', 'contact_format_default'))), array('CRM_ContactsCommon', 'contact_format_default'), array('id'=>$prefix.'_secondary_counselor'));			
			$theme->assign('form_secondary_counselor', array(
							'label'=>__('Secondary Counselor'),
							'html'=>$secondary_counselor->toHtml()										
							));
							
			$secondary_hd = HTML_QuickForm::createElement('text', 'secondary_hd', _M('Secondary HD'), array('id'=>$prefix.'_secondary_hd')); 
			$theme->assign('form_secondary_hd', array(
							'label'=>__('Secondary HD'),
							'html'=>$secondary_hd->toHtml()										
							));
			
			$secondary_sd = HTML_QuickForm::createElement('text', 'secondary_sd', _M('Secondary SD'), array('id'=>$prefix.'_secondary_sd')); 
			$theme->assign('form_secondary_sd', array(
							'label'=>__('Secondary SD'),
							'html'=>$secondary_sd->toHtml()										
							));			
					
			$secondary_internetpackage = HTML_QuickForm::createElement('select', 'secondary_internet_package', __('Secondary Internet Package'), $internetpackages, array('id'=>$prefix.'_secondary_internet_package'));
			$theme->assign('form_secondary_internetpackage', array(
							'label'=>__('Secondary Internet Package'),
							'html'=>$secondary_internetpackage->toHtml()										
							));			
														
			$theme->assign('form_note',			array(
							'label'=>__('Note'),
							'html'=>'<input type="text" name="note" id="'.$prefix.'_note"></input>'));
							
			$theme->assign('just_close',
				array('open'=>'<a id="'.$prefix.'_just_close_button" onclick="if(check_if_'.$prefix.'_set_deploymentdate()){'.$prefix.'_followups_deactivate();'.$prefix.'_set_action(\'resolve\');'.$prefix.'_submit_form();}">',
				'text'=>__( 'Save'),
				'close'=>'</a>')
			);
			
			$theme->assign('form_close','</form>');
			ob_start();
			Base_ThemeCommon::load_css('SCTV_Requirement','status',false); 
			Base_ThemeCommon::display_smarty($theme,'SCTV_Requirement','status');
			$profiles_out = ob_get_clean();

			Libs_LeightboxCommon::display($prefix.'_followups_leightbox',$profiles_out,__( 'Requirement Status'));	
		}		
	}
	public static function drawLeightboxCharge($prefix) {
		if(MOBILE_DEVICE) return;
		self::check_location();
		if (!isset(self::$leightbox_ready[$prefix])) {
			self::$leightbox_ready[$prefix] = true;

			$theme = Base_ThemeCommon::init_smarty();
			
			$theme->assign('form_requirement_code', array('label'=>__('Requirement Code')));
			$theme->assign('form_customer_name', array('label'=>__('Customer Name')));
			$theme->assign('form_street', array('label'=>__('Address')));
			$theme->assign('form_phone', array('label'=>__('Phone')));
			$theme->assign('form_cable_status', array('label'=>__('Cable Status')));
			$theme->assign('form_internetpackage', array('label'=>__('Internet Package')));
			$theme->assign('form_bundle', array('label'=>__('Bundle')));
			
			eval_js_once($prefix.'_followups_deactivate = function(){leightbox_deactivate(\''.$prefix.'_followups_leightbox\');}');
		
			eval_js($prefix.'_submit_form = function () {'.
						'$(\''.$prefix.'_follow_up_form\').submited.value=1;Epesi.href($(\''.$prefix.'_follow_up_form\').serialize(), \'processing...\');$(\''.$prefix.'_follow_up_form\').submited.value=0;'.
					'}');
			eval_js($prefix.'_set_action = function (arg) {'.
						'document.forms["'.$prefix.'_follow_up_form"].action.value = arg;'.
					'}');
			eval_js($prefix.'_set_id = function (id, name, street, phone, cable_status, hd, sd, internetpackage, bundle, charge) {'.
						'document.forms["'.$prefix.'_follow_up_form"].id.value = id;'.
						'$("form_charge_requirement_code").innerHTML ="#"+id;'.											
						'$("form_charge_customer_name").innerHTML =name;'.
						'$("form_charge_street").innerHTML=street;'.
						'$("form_charge_phone").innerHTML=phone;'.
						'$("form_charge_cable_staus").innerHTML=cable_status;'.
						'$("form_charge_hd").innerHTML=hd;'.
						'$("form_charge_sd").innerHTML=sd;'.
						'$("form_charge_internetpackage").innerHTML=internetpackage;'.
						'$("form_charge_bundle").innerHTML=bundle;'.
						'$("'.$prefix.'_charge").value=charge;'.
					'}');
					
			$theme->assign('form_open','<form id="'.$prefix.'_follow_up_form" name="'.$prefix.'_follow_up_form" method="POST">'.
							'<input type="hidden" name="submited" value="0" />'.
							'<input type="hidden" name="form_name" value="'.$prefix.'_follow_up_form" />'.
							'<input type="hidden" name="id" value="" />'.
							'<input type="hidden" name="action" value="" />');		
										
			$charge = HTML_QuickForm::createElement('text', 'charge', _M('Charge'), array('id'=>$prefix.'_charge'));
			$theme->assign('form_charge', array(
							'label'=>__('Charge'),
							'html'=>$charge->toHtml()										
							));
									
			$theme->assign('just_close',
				array('open'=>'<a id="'.$prefix.'_just_close_button" onclick="'.$prefix.'_followups_deactivate();'.$prefix.'_set_action(\'resolve\');'.$prefix.'_submit_form();">',
				'text'=>__( 'Save'),
				'close'=>'</a>')
			);
			
			$theme->assign('form_close','</form>');
			ob_start();
			Base_ThemeCommon::load_css('SCTV_Requirement','charge',false); 
			Base_ThemeCommon::display_smarty($theme,'SCTV_Requirement','charge');
			$profiles_out = ob_get_clean();

			Libs_LeightboxCommon::display($prefix.'_followups_leightbox',$profiles_out,__( 'Charge'));	
		}		
	}
	public static function drawLeightboxCustomerCode($prefix) {
		if(MOBILE_DEVICE) return;
		self::check_location();
		if (!isset(self::$leightbox_ready[$prefix])) {
			self::$leightbox_ready[$prefix] = true;

			$theme = Base_ThemeCommon::init_smarty();
			
			$theme->assign('form_requirement_code', array('label'=>__('Requirement Code')));
			$theme->assign('form_customer_name', array('label'=>__('Customer Name')));
			$theme->assign('form_street', array('label'=>__('Address')));
			$theme->assign('form_phone', array('label'=>__('Phone')));
			$theme->assign('form_cable_status', array('label'=>__('Cable Status')));
			$theme->assign('form_internetpackage', array('label'=>__('Internet Package')));
			$theme->assign('form_bundle', array('label'=>__('Bundle')));
			
			eval_js_once($prefix.'_followups_deactivate = function(){leightbox_deactivate(\''.$prefix.'_followups_leightbox\');}');
		
			eval_js($prefix.'_submit_form = function () {'.
						'$(\''.$prefix.'_follow_up_form\').submited.value=1;Epesi.href($(\''.$prefix.'_follow_up_form\').serialize(), \'processing...\');$(\''.$prefix.'_follow_up_form\').submited.value=0;'.
					'}');
			eval_js($prefix.'_set_action = function (arg) {'.
						'document.forms["'.$prefix.'_follow_up_form"].action.value = arg;'.
					'}');
			eval_js($prefix.'_set_id = function (id, name, street, phone, cable_status, hd, sd, internetpackage, bundle) {'.
						'document.forms["'.$prefix.'_follow_up_form"].id.value = id;'.
						'$("form_customer_code_requirement_code").innerHTML ="#"+id;'.											
						'$("form_customer_code_customer_name").innerHTML =name;'.
						'$("form_customer_code_street").innerHTML=street;'.
						'$("form_customer_code_phone").innerHTML=phone;'.
						'$("form_customer_code_cable_staus").innerHTML=cable_status;'.
						'$("form_customer_code_hd").innerHTML=hd;'.
						'$("form_customer_code_sd").innerHTML=sd;'.
						'$("form_customer_code_internetpackage").innerHTML=internetpackage;'.
						'$("form_customer_code_bundle").innerHTML=bundle;'.
					'}');
					
			$theme->assign('form_open','<form id="'.$prefix.'_follow_up_form" name="'.$prefix.'_follow_up_form" method="POST">'.
							'<input type="hidden" name="submited" value="0" />'.
							'<input type="hidden" name="form_name" value="'.$prefix.'_follow_up_form" />'.
							'<input type="hidden" name="id" value="" />'.
							'<input type="hidden" name="action" value="" />');		
										
			$customer_code = HTML_QuickForm::createElement('text', 'customer_code', _M('Customer Code'), array('id'=>$prefix.'_customer_code'));
			$theme->assign('form_customer_code', array(
							'label'=>__('Customer Code'),
							'html'=>$customer_code->toHtml()										
							));
									
			$theme->assign('just_close',
				array('open'=>'<a id="'.$prefix.'_just_close_button" onclick="'.$prefix.'_followups_deactivate();'.$prefix.'_set_action(\'resolve\');'.$prefix.'_submit_form();">',
				'text'=>__( 'Save'),
				'close'=>'</a>')
			);
			
			$theme->assign('form_close','</form>');
			ob_start();
			Base_ThemeCommon::load_css('SCTV_Requirement','customer_code',false); 
			Base_ThemeCommon::display_smarty($theme,'SCTV_Requirement','customer_code');
			$profiles_out = ob_get_clean();

			Libs_LeightboxCommon::display($prefix.'_followups_leightbox',$profiles_out,__( 'Customer Code'));	
		}		
	}

	public static function get_danang_id()
	{
		return Utils_CommonDataCommon::get_id('Countries/VN/DN');
	}

    public static function get_quangninh_id() {
        return Utils_CommonDataCommon::get_id('Countries/VN/QN');
    }

	public static function get_report_deployment_all($start_date, $end_date)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_deployment_all(%d, %T, %T)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date));
		return $recs;
	}	
	public static function get_report_deployment_counselor($start_date, $end_date, $counselor)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_deployment_counselor(%d, %T, %T, %d)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date, $counselor));
		return $recs;
	}
	public static function get_report_deployment_employee($start_date, $end_date, $employee)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_deployment_employee(%d, %T, %T, %d)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date, $employee));
		return $recs;
	}
	public static function get_report_deployment_department($start_date, $end_date, $department)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_deployment_department(%d, %T, %T, %d)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date, $department));
		return $recs;
	}
	public static function get_report_deployment_area($start_date, $end_date, $area)
	{
		if($area == null)
			$recs = DB::Execute("SELECT * FROM sctv_report_deployment_area(%d, %T, %T, null)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date));
		else
			$recs = DB::Execute("SELECT * FROM sctv_report_deployment_area(%d, %T, %T, %d)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date, $area));
		return $recs;
	}
	public static function get_report_marketing_all($start_date, $end_date)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_marketing_all(%d, %T, %T)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date));
		return $recs;
	}
	public static function get_report_marketing_counselor($start_date, $end_date, $counselor)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_marketing_counselor(%d, %T, %T, %d)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date, $counselor));
		return $recs;
	}
	public static function get_report_marketing_department($start_date, $end_date, $department)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_marketing_department(%d, %T, %T, %d)", array(SCTV_RequirementCommon::get_quangninh_id(), $start_date, $end_date, $department));
		return $recs;
	}
	public static function get_report_status($status)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_status(%d, %s)", array(SCTV_RequirementCommon::get_quangninh_id(), $status));
		return $recs;
	}
	public static function get_report_todo($todo)
	{
		$recs = DB::Execute("SELECT * FROM sctv_report_todo(%d, %s)", array(SCTV_RequirementCommon::get_quangninh_id(), $todo));
		return $recs;
	}
	public static function get_cable_status_name($cable_status)
	{		
		return $cable_status == null?'---':($cable_status == 1?__('New cable'):__('Addition cable'));
	}
	public static function get_lend_wifi_name($lend_wifi)
	{		
		return $lend_wifi == null?__('No'):($lend_wifi == 1?__('Yes'):__('No'));
	}
    public static function create_business($deployment_cable_status, $deployment_internet_package, $deployment_bundle, $deployment_bundle_text)
    {
        if(empty($deployment_cable_status) && $deployment_cable_status != '0')
        {
            if(empty($deployment_internet_package))
            {
                if(empty($deployment_bundle))
                {
                }
                else
                {
                    $business = "Chuyển trọn gói " . $deployment_bundle_text;
                }
            }
            else
            {
                if(empty($deployment_bundle))
                {
                    $business = "Lắp mới Internet";
                }
                else
                {
                    $business = "Lắp mới Internet" . " chuyển trọn gói " . $deployment_bundle_text;
                }
            }
        }
        else if($deployment_cable_status == 1)
        {
            if(empty($deployment_internet_package))
            {
                if(empty($deployment_bundle))
                {
                    $business = "Lắp mới THC";
                }
                else
                {
                    $business = "Lắp mới THC" . " chuyển trọn gói " . $deployment_bundle_text;
                }
            }
            else
            {
                if(empty($deployment_bundle))
                {
                    $business = "Lắp mới THC và Internet";
                }
                else
                {
                    $business = "Lắp mới trọn gói " . $deployment_bundle_text;
                }
            }
        }
        elseif($deployment_cable_status == 0)
        {
            if(empty($deployment_internet_package))
            {
                if(empty($deployment_bundle))
                {
                    $business = "Lắp thêm THC";
                }
                else
                {
                    $business = "Lắp thêm THC chuyển trọn gói " . $deployment_bundle_text;
                }
            }
            else
            {
                if(empty($deployment_bundle))
                {
                    $business = "Lắp thêm THC và lắp mới Internet";
                }
                else
                {
                    $business = "Lắp thêm THC và lắp mới Internet chuyển trọn gói " . $deployment_bundle_text;
                }
            }
        }

        return $business;
    }
}
 
?>